<template>
  <div>
    <el-card class="top">
      <el-button
        type="danger"
        @click="onExcelExport"
      >
        普通excel导出
      </el-button>
      <el-button
        type="primary"
        @click="onBtn"
      >
        新增员工
      </el-button>
    </el-card>
    <!-- 新增员工 -->
    <el-dialog
      title="新增员工"
      :visible.sync="addVisible"
      width="400"
    >
      <el-form :model="ruleForm" :rules="rules"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="入职时间">
          <el-col :span="11">
            <el-form-item prop="timeOfEntry">
              <el-date-picker type="date" placeholder="选择入职日期" v-model="ruleForm.timeOfEntry" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2"></el-col>
        </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="ruleForm.formOfEmployment" placeholder="请输入聘用形式">
              <el-option label="正式" value="1" key="1"></el-option>
              <el-option label="非正式" value="2" key="2"></el-option>
            </el-select>
          </el-form-item>
         <el-form-item label="工号" prop="workNumber">
          <el-input v-model="ruleForm.workNumber" placeholder="请输入工号"></el-input>
        </el-form-item>
         <el-form-item label="部门" prop="departmentName">
          <el-input :value="ruleForm.departmentName" placeholder="请输入部门" @click.native="showDepartmentTree">
          </el-input>
          <el-tree :data="departmentTree" :props="{ children: 'children',label: 'name'}" @node-click="onDepartmentTreeNodeClick"  default-expand-all v-show="departmentTreeVisible"/>
        </el-form-item>
         <el-form-item label="转正时间" >
          <el-col :span="11">
            <el-form-item prop="correctionTime">
              <el-date-picker type="date" placeholder="选择转正日期" v-model="ruleForm.correctionTime" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2"></el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onAddEmployeeClose">取 消</el-button>
        <el-button type="primary" @click="onAddStaff">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 员工列表 -->
    <my-table
       class="container"
      :table-props="{
        data: staffList.rows,
        border: true
      }"
      :columns="[
        { label: '序号', prop: 'index', width: 180, align: 'center', sortable: true, },
        { label: '姓名', prop: 'username', width: 180, align: 'center', sortable: true},
        { label: '头像', slotName: 'staffPhoto', width: 180, align: 'center' },
        { label: '手机号', prop: 'mobile', width: 180, align: 'center', sortable: true, },
        { label: '工号', prop: 'workNumber', width: 180, align: 'center', sortable: true, },
        { label: '聘用形式', prop: 'formOfEmployment', sortable: true, align: 'center', width: 180 },
        { label: '部门', prop: 'departmentName', align: 'center', sortable: true, width: 180},
        { label: '入职时间', prop: 'timeOfEntry', align: 'center', sortable: true, width: 180},
        { label: '状态', width: 180, align: 'center', slotName: 'status', width: 180},
        { label: '操作', width: 180, align: 'center', slotName: 'handle', width: 300,},
      ]"

      :pagination-props="{
        layout: 'total, sizes, prev, pager, next, jumper',
        total: staffList.total,
        currentPage: currentPage,
        pageSize: pageSize,
        pageSizes: [10, 20, 30, 40],

      }"
      :pagination-events="{
        'current-change': onCurrentPageChange,
        'size-change': onPageSizeChange
      }"
    >
      <template #status>
        <el-switch :value="true"></el-switch>
      </template>
      <template v-slot:handle="scope" :fixed="right">
        <el-button type="text">查看</el-button>
        <el-button type="text">转正</el-button>
        <el-button type="text">调岗</el-button>
        <el-button type="text">离职</el-button>
        <el-button type="text" @click="onRoleClick(scope.row.id)">角色</el-button>
        <el-button type="text" @click="onDelete(scope.row.id)">删除</el-button>
      </template>
      <template v-slot:staffPhoto="scope">
        <div class="avatar">
          <img :src="scope.row.staffPhoto">
        </div>
      </template>
    </my-table>

    <!-- 角色详情 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDetailVisible"
      width="300"
    >

      <el-checkbox-group
        v-model="roleDetailCheckList"
        v-loading="loading"
      >
        <el-checkbox
          v-for="item in roleList.rows"
          :key="item.id"
          :label="item.id"

        >
          {{item.name}}

        </el-checkbox>
      </el-checkbox-group>

      <span slot="footer" class="dialog-footer">
        <el-button @click="onRoleDetailClose">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 是否删除 -->
    <el-dialog
      title="提示"
      :visible.sync="deleteVisible"
      width="300"
    >
      <span>是否删除该用户</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="onDeleteOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

let currentId = null;
import ExcelJS from 'exceljs'
import { mapActions, mapState, mapGetters } from 'vuex';
import * as staffApi from '../../api/staff';
import * as roleApi from'../../api/role-management';
export default {
  name: 'Staff',
  data() {
    const validateUsername = (rule, value, callback) => {
      const telReg = /^1[3-9]\d{9}$/
      if (!telReg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      pageSize: 10,
      value: true,
      roleDetailVisible: false,
      roleDetailCheckList: [],
      loading: false,
      deleteVisible: false,
      addVisible: false,
      departmentTreeVisible: false,
      ruleForm: {
        name: '',
        mobile: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        type: [],
        departmentName: '',
        correctionTime: ''
        },

        rules: {
          name: [
            { required: true, message: '请输入名字', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入正确的手机号', trigger: 'blur', validator: validateUsername }
          ],
          timeOfEntry: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'blur' }
          ],
          formOfEmployment: [
            { required: true, message: '请选择聘用形式' }
          ],
          workNumber: [
            { required: true, message: '请输入工号', trigger: 'blur' }
          ],
          departmentName: [
            { required: true, message: '请选择部门' }
          ],
          correctionTime: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'blur' }
          ]
        }
    }
  },
  computed: {
    ...mapState('staff', ['staffList']),
    ...mapGetters('department', ['departmentTree']),
    ...mapState('role', ['roleList', 'roleDetailsList']),
  },
  methods: {
    ...mapActions('staff', ['updateStaffList']),
    ...mapActions('department', ['updateDepartmentList']),
    ...mapActions('role', ['updateRoleList', 'updateRoleDetailsList']),
    onCurrentPageChange(val) {
      this.currentPage = val
      this.updateStaffList({
        page: this.currentPage,
        size: this.pageSize
      })
    },
    onPageSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.updateStaffList({
        page: this.currentPage,
        size: this.pageSize
      })
    },
   async onRoleClick(id) {
      this.roleDetailVisible = true;
      this.loading = true;
      // 反显
      await this.updateRoleDetailsList(id);
      this.roleDetailCheckList = this.roleDetailsList.roleIds;
      this.loading = false;
      currentId = id;
    },
    onConfirm() {
      this.roleDetailVisible = false;
      staffApi.role(this.roleDetailCheckList, currentId)

    },
    onRoleDetailClose() {
      this.roleDetailVisible = false;
      this.roleDetailCheckList = []
    },
    onDelete(id) {
      this.deleteVisible = true;
      currentId = id;
    },
    async onDeleteOk() {
      this.deleteVisible = false;
      await roleApi.deleteRole(currentId)
             .then(msg => this.$message.success(msg))
             .catch(msg => this.$message.error(msg))
      this.updateStaffList({
      page: this.currentPage,
      size: this.pageSize
      })
    },
    onBtn() {
      this.addVisible = true
    },
    onAddStaff(){
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          await staffApi.addStaff({
          username: this.ruleForm.name,
          mobile: this.ruleForm.mobile,
          formOfEmployment: this.ruleForm.formOfEmployment,
          workNumber: this.ruleForm.workNumber,
          departmentName: this.ruleForm.departmentName,
          timeOfEntry: this.ruleForm.timeOfEntry,
          correctionTime: this.ruleForm.correctionTime,
        })
          .then(msg => this.$message.success(msg))
          .catch(msg => this.$message.error(msg))
        this.updateStaffList({
          page: this.currentPage,
          size: this.pageSize
        });
        this.addVisible = false;
        } else {
          this.$message.error('请输入完整信息');
        }
      });
    },
    onDepartmentTreeNodeClick(data) {
      this.departmentTreeVisible = false;
      this.ruleForm.departmentName = data.name
    },
    showDepartmentTree() {
      this.departmentTreeVisible = true
    },
    onAddEmployeeReset() {
      this.$refs.ruleForm.resetFields()
      this.departmentTreeVisible = false
    },
    onAddEmployeeClose() {
      this.addVisible = false;
      this.onAddEmployeeReset()
    },
     async onExcelExport() {
      this.exportLoading = true
      const employeeList = await staffApi.getAllEmployeeList()

      // 导出excel
      const workbook = new ExcelJS.Workbook()
      const sheet = workbook.addWorksheet('Sheet1')
      // 数组方式
      // const rows = [
      //   ['序号', '姓名', '手机号', '工号', '聘用形式', '部门', '入职时间'],
      //   ...employeeList.rows.map(r => [
      //     r.index,
      //     r.username,
      //     r.mobile,
      //     r.workNumber,
      //     r.formOfEmployment,
      //     r.departmentName,
      //     r.timeOfEntry
      //   ])
      // ]
      // 对象方式
      // 定义表头
      sheet.columns = [
        { header: '序号', key: 'index', width: 10 },
        { header: '姓名', key: 'username', width: 10 },
        { header: '手机号', key: 'mobile', width: 10 },
        { header: '工号', key: 'workNumber', width: 10 },
        { header: '聘用形式', key: 'formOfEmployment', width: 10 },
        { header: '部门', key: 'departmentName', width: 10 },
        { header: '入职时间', key: 'timeOfEntry', width: 10 }
      ]
      sheet.addRows(employeeList.rows)
      const buffer = await workbook.xlsx.writeBuffer()

      // 用来把一大堆数字变成文件的东西
      const blob = new Blob([buffer])

      const fileName = `嘿嘿.xlsx`
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
      link.click()
      window.URL.revokeObjectURL(link.href)
      link.remove()

      this.exportLoading = false
    }
  },

  created() {
    this.updateStaffList({
      page: this.currentPage,
      size: this.pageSize
    });
    this.updateRoleList({
      page: this.currentPage,
      size: this.pageSize
    });
    this.updateDepartmentList()
  },
  // watch: {
  //   checkList: {
  //     deep: true,
  //     handler(newValue) {
  //       console.log(newValue)
  //     }
  //   },
  // }
}
</script>

<style lang="scss" scoped>
@import "../../styles/common.scss";

.container {
  @include avatar(20px);

  // .avatar {
  //   display: flex;
  //   justify-content: center;
  // }
  // padding: 16px;


}
.top {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}
.block {
  display: flex;
  justify-content: flex-end;
}
</style>
